package lib.persistence.commands;

import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.mysql.jdbc.ResultSet;

import lib.Field;
import lib.reflection.Reflector;

public class InsertRow extends CommandAbstract {

	private Connection conn;

	public InsertRow(Connection conn) 
	{
		this.conn = conn;
	}
	public InsertRow() {
		this.conn = global.ConnectionManager.getInstance().getConnection();
	}
	/**
	 * Returns the id of the newly-created row
	 * @param fields
	 * @param tableName
	 * @return
	 * @throws  
	 * @throws SQLException 
	 * @throws Exception
	 */
	public int execute(List<Field> fields, String tableName) throws SQLException 
	{		
		PreparedStatement statement = conn.prepareStatement(getSql(fields, tableName));
		
		int fieldCount = fields.size();
		for (int i =0; i< fieldCount; i++) 
			setParameter(fields, statement, i);

		statement.executeUpdate();
		
		java.sql.ResultSet rs = statement.getGeneratedKeys();
		if (rs.next())
			return rs.getInt(1);
		return -1;
	}
	private String getSql(List<Field> fields, String tableName) {
		String cmd = String.format("INSERT INTO `%s` (",tableName);
		int fieldCount = fields.size();
		for (int i =0; i< fieldCount; i++) 
		{
			cmd = cmd.concat(fields.get(i).getName());
			if (i + 1 < fieldCount)
				cmd = cmd.concat(",");
		}
		cmd = cmd.concat(") VALUES (");
		for (int i =0; i< fieldCount; i++) 
		{
			cmd = cmd.concat("?");
			if (i + 1 < fieldCount)
				cmd = cmd.concat(",");
		}
		cmd = cmd.concat(")");
		System.out.println(cmd);
		return cmd;
	}
	
}
